package com.sicheng.metadata.设计模式.工厂.简单工厂;

import java.lang.reflect.InvocationTargetException;

/**
 * @author zsc
 * @version 1.0
 * @date 2022/11/8 19:08
 */
public class 支付案例 {
    interface IPay {
        String getName();

        Double queryBalance(String uid);

        default void pay(String uid, Double price) {
            Double currentAmount = queryBalance(uid);
            if (currentAmount < price) {
                System.out.println(getName() + "余额不足");
            } else {
                System.out.println(getName() + "支付成功");
            }
        }
    }

    static class AliPay implements IPay {
        @Override
        public String getName() {
            return "支付宝";
        }

        @Override
        public Double queryBalance(String uid) {
            return 900.0;
        }
    }

    static class WechatPay implements IPay {

        @Override
        public String getName() {
            return "微信";
        }

        @Override
        public Double queryBalance(String uid) {
            return 900.0;
        }
    }

    static class UnionPay implements IPay {
        @Override
        public String getName() {
            return "银行卡";
        }

        @Override
        public Double queryBalance(String uid) {
            return null;
        }
    }

    // 简单工厂模式 利用反射避免大量的if来判断生产的对象
    static class PayFactory {
        static IPay produce(Class<? extends IPay> clz) {
            try {
                return clz.getDeclaredConstructor().newInstance();
            } catch (NoSuchMethodException | InstantiationException | IllegalAccessException |
                    InvocationTargetException e) {
                e.printStackTrace();
            }
            return null;
        }
    }


    public static void main(String[] args) {
        IPay pay1 = PayFactory.produce(AliPay.class);
        IPay pay2 = PayFactory.produce(WechatPay.class);
        IPay pay3 = PayFactory.produce(UnionPay.class);
        System.out.println(pay1.getName());
        System.out.println(pay2.getName());
        System.out.println(pay3.getName());
    }
}
